package cn.zf233.springsecurityjwt.config.sms;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zf233 on 2021/7/12
 */
public class SmsLoginFilter extends AbstractAuthenticationProcessingFilter {

    public SmsLoginFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
        super(requiresAuthenticationRequestMatcher);
    }

    @Override
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String phoneNo = request.getParameter("phone");
        String code = request.getParameter("code");

        if (phoneNo == null) {
            phoneNo = "";
        }
        if (code == null) {
            code = "";
        }

        SmsAuthenticationToken token = new SmsAuthenticationToken(phoneNo, code);
        //token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));/
        token.setDetails(this.authenticationDetailsSource.buildDetails(request));
        return super.getAuthenticationManager().authenticate(token);
    }

}